package com.hotel.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotel.common.Result;
import com.hotel.entity.Bill;
import com.hotel.service.BillService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;

/**
 * 账单管理控制器
 * 
 * @author Hotel Management Team
 */
@RestController
@RequestMapping("/bill")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class BillController {

    private final BillService billService;

    /**
     * 分页查询账单
     */
    @GetMapping("/list")
    public Result<Page<Bill>> getBillPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String paymentStatus,
            @RequestParam(required = false) Long checkinId) {
        
        // 构建查询条件
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Bill> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like("bill_no", keyword);
        }
        
        if (paymentStatus != null && !paymentStatus.trim().isEmpty()) {
            queryWrapper.eq("payment_status", paymentStatus);
        }
        
        if (checkinId != null) {
            queryWrapper.eq("checkin_id", checkinId);
        }
        
        queryWrapper.orderByDesc("create_time");
        
        Page<Bill> page = new Page<>(current, size);
        Page<Bill> result = billService.page(page, queryWrapper);
        
        return Result.success(result);
    }

    /**
     * 获取账单详情
     */
    @GetMapping("/{id}")
    public Result<Bill> getBillById(@PathVariable Long id) {
        Bill bill = billService.getById(id);
        if (bill != null) {
            return Result.success(bill);
        } else {
            return Result.error("账单不存在");
        }
    }

    /**
     * 根据账单号获取账单
     */
    @GetMapping("/number/{billNo}")
    public Result<Bill> getBillByNumber(@PathVariable String billNo) {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Bill> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("bill_no", billNo);
        
        Bill bill = billService.getOne(queryWrapper);
        if (bill != null) {
            return Result.success(bill);
        } else {
            return Result.error("账单不存在");
        }
    }

    /**
     * 创建账单
     */
    @PostMapping
    public Result<Void> createBill(@Valid @RequestBody Bill bill) {
        // 生成账单号
        if (bill.getBillNo() == null || bill.getBillNo().trim().isEmpty()) {
            bill.setBillNo(generateBillNumber());
        }
        
        boolean success = billService.save(bill);
        if (success) {
            return Result.success("账单创建成功");
        } else {
            return Result.error("账单创建失败");
        }
    }

    /**
     * 更新账单
     */
    @PutMapping("/{id}")
    public Result<Void> updateBill(@PathVariable Long id, @Valid @RequestBody Bill bill) {
        bill.setId(id);
        boolean success = billService.updateById(bill);
        if (success) {
            return Result.success("账单更新成功");
        } else {
            return Result.error("账单更新失败");
        }
    }

    /**
     * 删除账单
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteBill(@PathVariable Long id) {
        boolean success = billService.removeById(id);
        if (success) {
            return Result.success("账单删除成功");
        } else {
            return Result.error("账单删除失败");
        }
    }

    /**
     * 根据入住记录ID获取账单
     */
    @GetMapping("/checkin/{checkinId}")
    public Result<Bill> getBillByCheckinId(@PathVariable Long checkinId) {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Bill> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("checkin_id", checkinId);
        
        Bill bill = billService.getOne(queryWrapper);
        if (bill != null) {
            return Result.success(bill);
        } else {
            return Result.error("账单不存在");
        }
    }

    /**
     * 支付账单
     */
    @PutMapping("/{id}/pay")
    public Result<Void> payBill(
            @PathVariable Long id,
            @RequestParam BigDecimal amount,
            @RequestParam String paymentMethod) {
        
        Bill bill = billService.getById(id);
        if (bill == null) {
            return Result.error("账单不存在");
        }
        
        // 更新已付金额
        BigDecimal newPaidAmount = bill.getPaidAmount().add(amount);
        bill.setPaidAmount(newPaidAmount);
        bill.setPaymentMethod(paymentMethod);
        
        // 更新支付状态
        if (newPaidAmount.compareTo(bill.getTotalAmount()) >= 0) {
            bill.setPaymentStatus("paid");
        } else if (newPaidAmount.compareTo(BigDecimal.ZERO) > 0) {
            bill.setPaymentStatus("partial");
        }
        
        boolean success = billService.updateById(bill);
        if (success) {
            return Result.success("支付成功");
        } else {
            return Result.error("支付失败");
        }
    }

    /**
     * 获取未支付账单
     */
    @GetMapping("/unpaid")
    public Result<List<Bill>> getUnpaidBills() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Bill> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("payment_status", "unpaid")
                   .orderByDesc("create_time");
        
        List<Bill> bills = billService.list(queryWrapper);
        return Result.success(bills);
    }

    /**
     * 获取部分支付账单
     */
    @GetMapping("/partial-paid")
    public Result<List<Bill>> getPartialPaidBills() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Bill> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("payment_status", "partial")
                   .orderByDesc("create_time");
        
        List<Bill> bills = billService.list(queryWrapper);
        return Result.success(bills);
    }

    /**
     * 生成账单号
     */
    private String generateBillNumber() {
        return "BILL" + System.currentTimeMillis();
    }

    /**
     * 获取账单统计信息
     */
    @GetMapping("/stats")
    public Result<java.util.Map<String, Object>> getBillStats() {
        java.util.Map<String, Object> stats = new java.util.HashMap<>();
        
        // 总账单数
        long totalBills = billService.count();
        stats.put("totalBills", totalBills);
        
        // 未支付账单数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Bill> unpaidWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        unpaidWrapper.eq("payment_status", "unpaid");
        long unpaidBills = billService.count(unpaidWrapper);
        stats.put("unpaidBills", unpaidBills);
        
        // 已支付账单数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Bill> paidWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        paidWrapper.eq("payment_status", "paid");
        long paidBills = billService.count(paidWrapper);
        stats.put("paidBills", paidBills);
        
        // 部分支付账单数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Bill> partialWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        partialWrapper.eq("payment_status", "partial");
        long partialBills = billService.count(partialWrapper);
        stats.put("partialBills", partialBills);
        
        return Result.success(stats);
    }
}